package com.example.filemonitor;

import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_SOURCE = 100;
    private static final int REQUEST_CODE_DEST_PIC = 101;
    private static final int REQUEST_CODE_DEST_VIO = 102;
    private static final int REQUEST_MANAGE_STORAGE = 200;

    private TextView sourcePathTextView;
    private TextView destPathTextView_pic;
    private TextView destPathTextView_vio;
    private SharedPreferences prefs;

    Button selectSourceBtn;
    Button selectPicBtn;
    Button selectVioBtn;
    Button stopMonitorBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sourcePathTextView = findViewById(R.id.source_path);
        destPathTextView_pic = findViewById(R.id.dest_path_p);
        destPathTextView_vio = findViewById(R.id.dest_path_v);

        selectSourceBtn = findViewById(R.id.select_source);
        selectPicBtn = findViewById(R.id.select_dest_p);
        selectVioBtn = findViewById(R.id.select_dest_v);
        Button startMonitorBtn = findViewById(R.id.start_monitor);
        stopMonitorBtn = findViewById(R.id.stop_monitor);

        prefs = getSharedPreferences("FileMonitorPrefs", MODE_PRIVATE);
        loadSavedPaths();

        // 检查一加手机存储权限
        if (!isStorageManagerGranted()) {
            requestStoragePermission();
        }

        selectSourceBtn.setOnClickListener(v -> openDocumentTree(REQUEST_CODE_SOURCE));
        selectPicBtn.setOnClickListener(v -> openDocumentTree(REQUEST_CODE_DEST_PIC));
        selectVioBtn.setOnClickListener(v -> openDocumentTree(REQUEST_CODE_DEST_VIO));
        startMonitorBtn.setOnClickListener(v -> startMonitoring());
        stopMonitorBtn.setOnClickListener(v -> stopMonitoring());
    }

    // 适配一加手机的存储权限检查
    private boolean isStorageManagerGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        }
        return true;
    }

    // 请求一加手机的存储管理权限
    private void requestStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_MANAGE_STORAGE);
            } catch (Exception e) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivityForResult(intent, REQUEST_MANAGE_STORAGE);
            }
        }
    }

    // 打开文件夹选择器（适配一加文件管理器）
    private void openDocumentTree(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        // 一加手机特定配置，确保能正确显示所有存储位置
        intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                // 持久化URI权限（关键：确保一加手机重启后仍能访问）
                getContentResolver().takePersistableUriPermission(
                        uri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION |
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                );

                String path = getPathFromUri(uri);
                if (requestCode == REQUEST_CODE_SOURCE) {
                    savePath("source_uri", uri.toString());
                    sourcePathTextView.setText(path);
                } else if (requestCode == REQUEST_CODE_DEST_PIC) {
                    savePath("target_pic_uri", uri.toString());
                    destPathTextView_pic.setText(path);
                }else if (requestCode == REQUEST_CODE_DEST_VIO){
                    savePath("target_vio_uri", uri.toString());
                    destPathTextView_vio.setText(path);
                }
            }
        } else if (requestCode == REQUEST_MANAGE_STORAGE) {
            if (!isStorageManagerGranted()) {
                Toast.makeText(this, "请授予存储管理权限以正常使用", Toast.LENGTH_LONG).show();
            }
        }
    }

    // 从URI获取路径（适配一加手机的存储结构）
    private String getPathFromUri(Uri uri) {
        DocumentFile docFile = DocumentFile.fromTreeUri(this, uri);
        if (docFile != null && docFile.exists()) {
            return docFile.getName();
        }
        return uri.getPath();
    }

    private void loadSavedPaths() {
        String sourceUri = prefs.getString("source_uri", "");
        String tarPicUri = prefs.getString("target_pic_uri", "");
        String tarVioUri = prefs.getString("target_vio_uri", "");
        stopMonitorBtn.setVisibility(View.GONE);
        if (!sourceUri.isEmpty()) {
            selectSourceBtn.setVisibility(View.GONE);
//            sourcePathTextView.setText(getPathFromUri(Uri.parse(sourceUri)));
        }
        if (!tarPicUri.isEmpty()) {
            selectPicBtn.setVisibility(View.GONE);
//            destPathTextView_pic.setText(getPathFromUri(Uri.parse(tarPicUri)));
        }
        if (!tarVioUri.isEmpty()) {
            selectVioBtn.setVisibility(View.GONE);
//            destPathTextView_vio.setText(getPathFromUri(Uri.parse(tarVioUri)));
        }
    }

    private void savePath(String key, String value) {
        prefs.edit().putString(key, value).apply();
    }

    private void startMonitoring() {
        String sourceUri = prefs.getString("source_uri", "");
        String tarPicUri = prefs.getString("target_pic_uri", "");
        String tarVioUri = prefs.getString("target_vio_uri", "");

        if (sourceUri.isEmpty()) {
            Toast.makeText(this, "请先选择源端", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tarPicUri.isEmpty() || tarVioUri.isEmpty()){
            if (tarPicUri.isEmpty()){
                Toast.makeText(this, "请选择P端", Toast.LENGTH_SHORT).show();
            }else if (tarVioUri.isEmpty()){
                Toast.makeText(this, "请选择V端", Toast.LENGTH_SHORT).show();
            }
        }

        if (!isStorageManagerGranted()) {
            Toast.makeText(this, "请先授予存储权限", Toast.LENGTH_SHORT).show();
            requestStoragePermission();
            return;
        }

        Intent serviceIntent = new Intent(this, FileMonitorService.class);
        serviceIntent.putExtra("source_uri", sourceUri);
        serviceIntent.putExtra("target_pic_uri", tarPicUri);
        serviceIntent.putExtra("target_vio_uri", tarVioUri);

        // 适配Android 10+的前台服务启动方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }

        Toast.makeText(this, "monitor", Toast.LENGTH_SHORT).show();
    }

    private void stopMonitoring() {
        Intent serviceIntent = new Intent(this, FileMonitorService.class);
        stopService(serviceIntent);
        Toast.makeText(this, "not monitor", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 服务会在后台继续运行，不会随Activity销毁而停止
    }
}